package com.legendshop.code.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.PatternMatcherInput;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

public class StringConverter {

    private StringConverter() {
    }

    public static String setFirstCharUpcase(String s) {
        if ((s == null) || (s.length() < 1)) {
            return s;
        }
        char c[] = s.toCharArray();
        if ((c.length > 0) && (c[0] >= 'a') && (c[0] <= 'z')) {
            c[0] = (char) ((short) c[0] - 32);
        }
        return String.valueOf(c);
    }

    public static String setFirstCharLowercase(String s) {
        if ((s == null) || (s.length() < 1)) {
            return s;
        }
        char c[] = s.toCharArray();
        if ((c.length > 0) && (c[0] >= 'A') && (c[0] <= 'Z')) {
            c[0] = (char) ((short) c[0] + 32);
        }
        return String.valueOf(c);
    }

    public static String[] toDataBaseString(String[] strs) {
        if ((strs == null) || (strs.length <= 0)) {
            return null;
        }
        String[] newStr = new String[strs.length];
        for (int i = 0; i < strs.length; i++) {
            newStr[i] = toDataBaseString(strs[i]);
        }
        return newStr;
    }

    public static String toDataBaseString(String str) {
        if ((str == null) || (str.trim().length() <= 0)) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        char[] cs = str.toCharArray();
        for (char element : cs) {
            if (Character.isUpperCase(element)) {//大写
                sb.append("_").append(element);
            } else if (Character.isLowerCase(element)) {//小写
                sb.append(Character.toUpperCase(element));
            } else {//其他的数字
                sb.append(element);
            }

        }

        return sb.toString();
    }

    public static String[] toBoString(String[] strs) {
        if ((strs == null) || (strs.length <= 0)) {
            return null;
        }
        String[] newStr = new String[strs.length];
        for (int i = 0; i < strs.length; i++) {
            newStr[i] = toBoString(strs[i]);
        }
        return newStr;
    }

    public static String toBoString(String str) {
        if ((str == null) || (str.trim().length() <= 0)) {
            return null;
        }
        StringBuffer sb = new StringBuffer();
        char[] cs = str.toLowerCase().toCharArray();
        for (int i = 0; i < cs.length; i++) {
            if ((cs[i] == '_') && (i == cs.length - 1)) {
                sb.append(cs[i]);
            } else if ((cs[i] == '_') && (i < cs.length - 1)) {
                sb.append(Character.toUpperCase(cs[i + 1]));
                i++;
            } else {
                sb.append(cs[i]);
            }

        }

        return sb.toString();
    }

    /**
     * 读入模版并将参数代进去
     * 
     * @param fileName
     * @throws MalformedPatternException
     */
    public static String convertTemplate(String fileName, String pattern, Map<String,String> values)
            throws MalformedPatternException {
        String record = null;
        StringBuffer sb = new StringBuffer();
        //int recCount = 0;
        try {
            File inFile = new File(fileName);
            if (!inFile.exists()) {
                return sb.toString();
            }
            FileInputStream fileInputStream = new FileInputStream(inFile);
            BufferedReader inBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));

            record = new String();
            while ((record = inBufferedReader.readLine()) != null) {
                //                recCount++;
                //                System.out.println(recCount + ": " + record);
                sb.append(convert(record, pattern, values) + "\n");
            }
            inBufferedReader.close();
            fileInputStream.close();
        } catch (IOException e) {
            System.out.println("got an IOException error!");
            e.printStackTrace();
        }
        return sb.toString();
    }
    

	/**
	 * 将text中带＃key＃的字符串换成map中的value.
	 * 
	 * @param text
	 *            the text
	 * @param patternString
	 *            the pattern string
	 * @param map
	 *            the map
	 * @return the string
	 * @throws MalformedPatternException
	 *             the malformed pattern exception
	 */
	public static String convert(String text, String patternString, Map map) throws MalformedPatternException {
		PatternMatcher matcher;
		PatternCompiler compiler;
		Pattern pattern;
		PatternMatcherInput input;
		MatchResult result;

		StringBuffer textBuf = new StringBuffer(text);
		compiler = new Perl5Compiler();
		pattern = compiler.compile(patternString);
		matcher = new Perl5Matcher();
		input = new PatternMatcherInput(text.toString());

		int offset = 0;
		String key = null;
		try {
			while (matcher.contains(input, pattern)) {
				result = matcher.getMatch();
				if (result != null && result.length() > 0) {
					int len = result.length();
					key = result.toString();
					String value = (String) map.get(key);
					textBuf.replace(result.beginOffset(0) + offset, result.endOffset(0) + offset, value);
					offset += value.length() - len;
				}
			}
		} catch (Exception e) {
			throw new RuntimeException("can not replace key  " + key, e);
		}

		return textBuf.toString();
	}

}